package com.example.demo.util;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class ImageDownload {

    public static void DownloadFile(String fileUrl,String saveDir) throws IOException {


        try {
            // 创建 URL 对象
            URL url = new URL(fileUrl);
            // 从 URL 获取文件名
            String fileName = new File(url.getPath()).getName();

            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();

            // 检查 HTTP 响应码
            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                System.out.println("下载失败: HTTP " + connection.getResponseCode());
                return;
            }

            // 获取文件的输入流
            InputStream inputStream = connection.getInputStream();
            // 创建文件的输出流
            FileOutputStream outputStream = new FileOutputStream(saveDir + File.separator + fileName);

            // 创建缓冲区
            byte[] buffer = new byte[4096];
            int bytesRead;
            // 将输入流中的数据写入到输出流
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }

            // 关闭流
            inputStream.close();
            outputStream.close();
            System.out.println("文件下载成功！");
        } catch (IOException e) {
            System.out.println("下载过程中发生错误: " + e.getMessage());
        }

    }

    public static void main(String[] args) throws IOException {
        String[] fileUrls = new String[]{"https://app-fuqi-prod-1321481675.cos.ap-shanghai.myqcloud.com/contract/20250123/自由职业者签约_30005304_3485131437_1737619683376.pdf"};
        for (int i = 0; i < fileUrls.length; i++) {
            DownloadFile(fileUrls[i],"D:/signfile");
        }
    }
}
